import { ResPage } from "@/api/interface";
import { Tag } from "@/api/interface/tag";
import { addTagApi, deleteTagApi, getTagListApi, updateTagApi } from "@/api/modules/tag";
import { RootThunkAction, store } from "@/redux";
import { RootDispatch } from "@/redux/interface";
import * as types from "@/redux/mutation-types";

export const setTagList = (payload: ResPage<Tag>) => {
	return {
		type: types.SET_TAG_LIST,
		payload
	};
};

export const setTagDetail = (payload: Partial<Tag>) => {
	return {
		type: types.SET_TAG_DETAIL,
		payload
	};
};

export const getTagList = async (pageNum: number = 1, pageSize: number = 10, wrapper?: Partial<Tag>) => {
	store.dispatch(getList(pageNum, pageSize, wrapper));
};

export const getTagDetail = (tag: Partial<Tag>) => {
	store.dispatch(setTagDetail(tag));
};

export const addTag = (tag: Tag) => {
	store.dispatch(add(tag));
};

export const updateTag = (tag: Tag) => {
	store.dispatch(update(tag));
};

export const removeTag = (id: number) => {
	store.dispatch(remove(id));
};

export const getList = (pageNum: number, pageSize: number, wrapper?: Partial<Tag>): RootThunkAction => {
	return async (dispatch: RootDispatch<ResPage<Tag>>) => {
		const res = await getTagListApi(pageNum, pageSize, wrapper);
		dispatch(setTagList(res.data));
	};
};

export const add = (tag: Tag): RootThunkAction => {
	return async dispatch => {
		const res = await addTagApi(tag);
		if (res.code === 200) getTagList();
	};
};

export const remove = (id: number): RootThunkAction => {
	return async dispatch => {
		const res = await deleteTagApi(id);
		if (res.code === 200) getTagList();
	};
};

export const update = async (tag: Tag) => {
	const res = await updateTagApi(tag);
	if (res.code === 200) return true;
	else return false;
};
